package com.kate.mall.bff.wx.service;

import cn.hutool.core.map.MapUtil;
import com.kate.mall.bff.wx.controller.form.SubmitOrderFrom;
import com.kate.mall.bff.wx.dto.OrderDTO;
import com.kate.mall.bff.wx.feign.OrderFeignClient;
import com.kate.mall.common.utils.ListMap2ListVoUtils;
import com.kate.mall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 用一句话描述
 * @Auther: 新梦想*陈超
 * @Date: 2021/8/18 23:18
 */
@Service
@Slf4j
public class OrderService {
    @Resource
    private OrderFeignClient orderFeignClient;

    public R createOrder(SubmitOrderFrom orderFrom) throws Exception {
        OrderDTO orderDTO = orderFrom.clone(OrderDTO.class);

        //TODO  3、计算团购优惠金额
        //实现团购价格计算 grouponRulesId
        if(!orderDTO.getGrouponRulesId().equals(0)){
            R grouponDiscountR = orderFeignClient.calculateGroupOnPrice(orderDTO);
            Double grouponDiscount = MapUtil.get(grouponDiscountR, "grouponDiscountPrice", Double.class);
            orderDTO.setGrouponPrice(new BigDecimal(String.valueOf(grouponDiscount)));
            //orderDTO.setGrouponPrice(new BigDecimal("0.0"));
            log.info("=========ndmall-wx-api计算团购优惠总价为：{}=====",orderDTO);
        }

        //TODO  4.计算订单总价格
        R orderPriceR = orderFeignClient.calculateOrderPrice(orderDTO);
        orderDTO = ListMap2ListVoUtils.map2Vo((Map)orderPriceR.get("order"), OrderDTO.class);
        log.info("=========ndmall-wx-api计算订单总价为：{}=====",orderDTO);
        //TODO  5、检测优惠券是否可用，可用则，使用优惠券减免的金额
        if(!orderDTO.getCouponId().equals(0)){
            R couponPriceR = orderFeignClient.calculateCouponPrice(orderDTO);
            BigDecimal couponAmount = MapUtil.get(couponPriceR,"couponAmount", BigDecimal.class);
            orderDTO.setCouponPrice(couponAmount);
            log.info("=========ndmall-wx-api计算优惠券总价为：{}=====",orderDTO);
        }

        //TODO  6.可以使用的其他钱，例如用户积分
        //TODO  待完善
        orderDTO.setIntegralPrice(new BigDecimal("0.0"));
        //TODO  7.创建订单
        R orderR  = orderFeignClient.saveOrder(orderDTO);
        orderDTO = ListMap2ListVoUtils.map2Vo((Map)orderR.get("data"), OrderDTO.class);
        log.info("=========ndmall-wx-api添加订单信息为：{}=====",orderDTO);
        Map<String, Object> data = new HashMap<>();
        data.put("orderId", orderDTO.getId());
        return R.ok().put("data", data);
    }

    /**
     * 预支付就是指，用户扫码支付了，但是必须通过商户系统必须通过支付平台的异步回调才能最终确认支付
     * @param body
     * @return
     */
    public R prepay(String body) {
        R  prepayResult = orderFeignClient.prepay(body);

        return R.ok();
    }
}